<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <div class="stats-header">
      <h2>平台统计</h2>
      <el-button type="primary" @click="refreshStats" :loading="statsLoading">
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
    </div>
    
    <div class="stats-grid">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon users">
            <el-icon :size="32"><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalUsers }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon products">
            <el-icon :size="32"><Goods /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalProducts }}</div>
            <div class="stat-label">总商品数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon orders">
            <el-icon :size="32"><List /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalOrders }}</div>
            <div class="stat-label">总订单数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon revenue">
            <el-icon :size="32"><Money /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">¥{{ formatRevenue(stats.totalRevenue) }}</div>
            <div class="stat-label">总交易额</div>
          </div>
        </div>
      </el-card>
    </div>

  

    <!-- 最新动态 -->
    <div class="recent-section">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>最新用户</span>
                <el-button text @click="refreshLatestUsers">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </template>
            <div v-loading="usersLoading" class="recent-list">
              <div
                v-for="user in recentUsers"
                :key="user.id"
                class="recent-item"
              >
                <el-avatar :size="40" :src="user.userAvatar">
                  {{ user.userName?.charAt(0)?.toUpperCase() || user.userAccount?.charAt(0)?.toUpperCase() || 'U' }}
                </el-avatar>
                <div class="item-info">
                  <div class="item-title">{{ user.userName || user.userAccount }}</div>
                  <div class="item-desc">{{ formatTime(user.createTime) }}</div>
                </div>
                <el-tag :type="user.userRole === 0 ? 'danger' : 'success'" size="small">
                  {{ user.userRole === 0 ? '管理员' : '用户' }}
                </el-tag>
              </div>
              
              <div v-if="recentUsers.length === 0 && !usersLoading" class="empty-state">
                <el-empty description="暂无用户数据" />
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>最新商品</span>
                <el-button text @click="refreshLatestProducts">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </template>
            <div v-loading="productsLoading" class="recent-list">
              <div
                v-for="product in recentProducts"
                :key="product.id"
                class="recent-item"
              >
                <el-image
                  :src="getProductImage(product.coverList)"
                  fit="cover"
                  style="width: 40px; height: 40px; border-radius: 4px; flex-shrink: 0;"
                />
                <div class="item-info">
                  <div class="item-title">{{ product.name }}</div>
                  <div class="item-desc">¥{{ product.price }} · {{ formatTime(product.createTime) }}</div>
                </div>
                <div class="product-tags">
                  <el-tag v-if="product.isBargain" type="success" size="small">可砍价</el-tag>
                  <el-tag type="info" size="small">{{ getOldLevelText(product.oldLevel) }}</el-tag>
                </div>
              </div>
              
              <div v-if="recentProducts.length === 0 && !productsLoading" class="empty-state">
                <el-empty description="暂无商品数据" />
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { User, Goods, List, Money, Refresh } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useProductStore } from '@/stores/product'
import { useOrderStore } from '@/stores/order'
import { getOldLevelText } from '@/utils/product'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const userStore = useUserStore()
const productStore = useProductStore()
const orderStore = useOrderStore()

// 统计数据
const stats = ref({
  totalUsers: 0,
  totalProducts: 0,
  totalOrders: 0,
  totalRevenue: 0
})

// 最新用户
const recentUsers = ref<any[]>([])
const usersLoading = ref(false)

// 最新商品
const recentProducts = ref<any[]>([])
const productsLoading = ref(false)

// 统计数据加载状态
const statsLoading = ref(false)

// 方法
const formatTime = (time: string) => {
  return dayjs(time).format('MM-DD HH:mm')
}

const formatRevenue = (amount: number) => {
  return amount.toLocaleString('zh-CN')
}

const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'warning'
    default: return 'info'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '下架'
    case 1: return '上架'
    case 2: return '已售'
    default: return '未知'
  }
}

// 获取最新用户
const loadLatestUsers = async () => {
  try {
    usersLoading.value = true
    const users = await userStore.getLatestUsers(4)
    recentUsers.value = users
  } catch (error) {
    console.error('获取最新用户失败:', error)
    ElMessage.error('获取最新用户失败')
  } finally {
    usersLoading.value = false
  }
}

// 刷新最新用户
const refreshLatestUsers = () => {
  loadLatestUsers()
}

// 获取最新商品
const loadLatestProducts = async () => {
  try {
    productsLoading.value = true
    const products = await productStore.getLatestProducts(4)
    recentProducts.value = products
  } catch (error) {
    console.error('获取最新商品失败:', error)
    ElMessage.error('获取最新商品失败')
  } finally {
    productsLoading.value = false
  }
}

// 刷新最新商品
const refreshLatestProducts = () => {
  loadLatestProducts()
}

// 获取商品图片
const getProductImage = (coverList: string) => {
  try {
    if (!coverList) return '/placeholder.svg'
    return coverList ? coverList : '/placeholder.svg'
  } catch {
    return '/placeholder.svg'
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    statsLoading.value = true
    // 并行获取所有统计数据
    const [userCount, productCount, orderCount, revenue] = await Promise.all([
      userStore.getUserCount(),
      productStore.getProductCount(),
      orderStore.getOrderCount(),
      orderStore.getTotalRevenue()
    ])
    
    stats.value = {
      totalUsers: userCount,
      totalProducts: productCount,
      totalOrders: orderCount,
      totalRevenue: revenue
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  } finally {
    statsLoading.value = false
  }
}

// 刷新统计数据
const refreshStats = () => {
  loadStats()
}

// 生命周期
onMounted(() => {
  // 加载统计数据
  loadStats()
  // 加载最新用户数据
  loadLatestUsers()
  // 加载最新商品数据
  loadLatestProducts()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

/* 统计头部样式 */
.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.stats-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

/* 统计卡片样式 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.stat-icon.users {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.products {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 图表区域样式 */
.charts-section {
  margin-bottom: 32px;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 最新动态样式 */
.recent-section {
  margin-bottom: 32px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recent-list {
  max-height: 400px;
  overflow-y: auto;
}

.recent-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.recent-item:last-child {
  border-bottom: none;
}

.item-info {
  flex: 1;
}

.item-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.item-desc {
  font-size: 12px;
  color: #909399;
}

.product-tags {
  display: flex;
  gap: 4px;
  flex-direction: column;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
  }
  
  .stat-number {
    font-size: 24px;
  }
}
</style> 